package com.chukun.flink.stream.operator.base;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple1;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author chukun
 * @version 1.0.0
 * @description flatmap 操作符
 * @createTime 2022年05月10日 00:06:00
 */
public class FlatMapOperator {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStream<Tuple2<String, Integer>> streamSource = env.fromElements(
                new Tuple2<>("liuyang", 1),
                new Tuple2<>("flink is fun", 2),
                new Tuple2<>("hello flink", 3)
        );

        DataStream<Tuple1<String>> resultStream = streamSource.flatMap(new FlatMapFunction<Tuple2<String, Integer>, Tuple1<String>>() {

            @Override
            public void flatMap(Tuple2<String, Integer> tuple2, Collector<Tuple1<String>> collector) throws Exception {
                if ("liuyang".equals(tuple2.f0)) {
                    return;
                }
                if (tuple2.f0.indexOf("fun") > 0) {
                    for (String word : tuple2.f0.split(" ")) {
                        collector.collect(new Tuple1<>("split.fun : " + word));
                    }
                } else {
                    collector.collect(new Tuple1<>("not.split.fun : " + tuple2.f1));
                }
            }
        });

        resultStream.print("输出结果");

        // 触发程序执行
        env.execute("flatMap stream");
    }
}
